<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AppBaseController;
use App\Repositories\ConfigRepository;
use App\Repositories\UsersRepository;
use App\User;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use Flash;
use Illuminate\Support\Facades\Auth;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

class UserController extends AppBaseController
{
    /** @var  userRepository */
    private $userRepository;

    public function __construct(UsersRepository $usersRepository)
    {
        $this->userRepository = $usersRepository;
    }

    /**
     * Display a listing of the User.
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $this->userRepository->pushCriteria(new RequestCriteria($request));
        $shop = Auth::guard('admin')->user()->shop;
        $users = User::where('shop_id',$shop->id)->paginate(10);

        return view('users.index')
            ->with('users', $users);
    }

    /**
     * Show the form for creating a new User.
     *
     * @return Response
     */
    public function create()
    {
        return view('users.create');
    }

    /**
     * Store a newly created User in storage.
     *
     * @param CreateUserRequest $request
     *
     * @return Response
     */
    public function store(Request $request)
    {
        $input = $request->all();

        $User = $this->userRepository->create($input);

        Flash::success('User saved successfully.');

        return redirect(route('users.index'));
    }

    /**
     * Display the specified User.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $User = $this->userRepository->findWithoutFail($id);

        if (empty($User)) {
            Flash::error('User not found');

            return redirect(route('users.index'));
        }

        return view('users.show')->with('User', $User);
    }

    /**
     * Show the form for editing the specified User.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $User = $this->userRepository->findWithoutFail($id);

        if (empty($User)) {
            Flash::error('User not found');

            return redirect(route('users.index'));
        }

        return view('users.edit')->with('User', $User);
    }

    /**
     * Update the specified User in storage.
     *
     * @param  int              $id
     * @param UpdateUserRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $User = $this->userRepository->findWithoutFail($id);

        if (empty($User)) {
            Flash::error('User not found');

            return redirect(route('users.index'));
        }

        $User = $this->userRepository->update($request->all(), $id);

        Flash::success('User updated successfully.');

        return redirect(route('users.index'));
    }

    /**
     * Remove the specified User from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        $User = $this->userRepository->findWithoutFail($id);

        if (empty($User)) {
            Flash::error('User not found');

            return redirect(route('users.index'));
        }

        $this->userRepository->delete($id);

        Flash::success('User deleted successfully.');

        return redirect(route('users.index'));
    }

    public function news()
    {
        $configRepository = app()->build(ConfigRepository::class);
        $configRepository->getWechatConfig(Auth::guard('admin')->user()->shop->wechat->id);
        $material = $configRepository->app->material;
        $news = $material->lists('news');
        $news = $news->first();
        return view('users.news')->with('news',$news);
    }

    public function images()
    {
        $configRepository = app()->build(ConfigRepository::class);
        $configRepository->getWechatConfig(Auth::guard('admin')->user()->shop->wechat->id);
        $material = $configRepository->app->material;
        $news = $material->lists('image');
        $news = $news->first();
        return view('users.images')->with('news',$news);
    }

    public function menus()
    {
        return view('users.menus');
    }

    public function getMenu()
    {
        $configRepository = app()->build(ConfigRepository::class);
        $wechat = Auth::guard('admin')->user()->shop->wechat;
        $configRepository->getWechatConfig($wechat->id);
        $menus = \request('menus');
        if($menus){
            $menu_b = $configRepository->app->menu;
            $buttons = [];
            foreach ($menus as $menu) {
                $_array = [];
                if(isset($menu['sub_button']) && !empty($menu['sub_button'])){
                    $_array['name'] = $menu['name'];
                    $chinld = [];
                    foreach ($menu['sub_button'] as $smenu) {

                        $chinld[] = $this->getMenuSetData($smenu);
                    }
                    $_array['sub_button'] = $chinld;
                    $buttons[] = $_array;
                }else{
                    $buttons[] = $this->getMenuSetData($menu);
                }
            }
            try
            {
                $res = $menu_b->add($buttons);
            }
            catch(\Exception $e)
            {
                return $this->ajaxReturn(['status'=>0,'data'=>$menus,'msg'=>$e->getMessage()]);
            }
            if(isset($res) && $res->errcode==0){
                $wechat->menus()->delete();
                $wechat->menus = json_encode($menus, 256);
                $wechat->save();
                return $this->ajaxReturn(['status'=>1,'data'=>$menus,'msg'=>'ok']);
            }else{
                return $this->ajaxReturn(['status'=>0,'data'=>$menus,'msg'=>$res->errmsg]);
            }
        }else{
            $menus = json_decode($wechat->menus, true);
            return $this->ajaxReturn(['status'=>1,'data'=>$menus,'msg'=>'list ok']);
        }
    }

    public function getMenuSetData($menu)
    {
        $array = [];
        $array['name'] = $menu['name'];
        switch ($menu['type']){
            case 'media_id':
                $array['type'] = $menu['type'];
                $array['media_id'] = $menu['media_id'];
                break;
            case 'view':
                $array['type'] = $menu['type'];
                $array['url'] = $menu['url'];
                break;
            case 'miniprogram':
                $array['type'] = $menu['type'];
                $array['url'] = $menu['url'];
                $array['appid'] = $menu['appid'];
                $array['pagepath'] = $menu['pagepath'];
                break;
            case 'text':
                $array['type'] = 'click';
                $array['key'] = $menu['name'];
                # TODO 需要保存文字回复
                break;
            default:
                break;
        }
        return $array;
    }

    public function ajaxReturn($arr)
    {
        return responseZK($arr['status'],$arr['data'],isset($arr['msg'])?$arr['msg']:null);
    }
}
